
#include <memory>  
#include "tcp_server.hpp"
#include "translate.hpp"
#include "daemon.hpp"

void Usage(const std::string &s)
{
    std::cout << "warning: illegal usage!" << std::endl;
    std::cout << "please input as this: " << s.c_str() << " server_port" << std::endl;
}

// 心跳机制---client访问server设置的短服务来判断服务器是否健康
void Ping(const int &sock_fd, InetAddr addr)
{
    lg.LogMessage(Info, "[%s] request: Ping success, fd: %d\n", addr.PrintAddr().c_str(), sock_fd);
    std::string response = "Server echo# success to receive ["; // 服务器应答
    response += addr.PrintAddr().c_str();
    response += "] Ping request";
    write(sock_fd, response.c_str(), response.size());
}
// 翻译器
void Translate(const int &sock_fd, InetAddr addr)
{

    lg.LogMessage(Info, "[%s] request: Translate success, fd: %d\n", addr.PrintAddr().c_str(), sock_fd);

    zhong::Translate t; // 定义翻译对象

    char word[128];
    int n = read(sock_fd, word, sizeof(word));
    if (n > 0)
    {
        word[n] = 0;
    }
    // 需要解决shell中的乱码问题
    std::string chinese = t.Excute(word).c_str();
    write(sock_fd, chinese.c_str(), chinese.size());
    lg.LogMessage(Info, "[%s] translate the word: [%s] -> %s\n", addr.PrintAddr().c_str(), word, chinese.c_str());
}
// 将小写转为大写
void Transform(const int &sock_fd, InetAddr addr)
{
    lg.LogMessage(Info, "[%s] request: Transform success, fd: %d\n", addr.PrintAddr().c_str(), sock_fd);
    char word[128];
    int n = read(sock_fd, word, sizeof(word));
    if (n > 0)
    {
        word[n] = 0;
    }
    // transform的逻辑
    std::string transfrom = word;
    for (size_t i = 0; i < transfrom.size(); i++)
    {
        // if (transfrom[i] < 'A' || (transfrom[i] < 'a' && transfrom[i] > 'Z') || transfrom[i] > 'z')
        // {
        //     transfrom[i] = transfrom[i+1];    // 将非法字符除去
        // }
        if (transfrom[i] >= 'a' && transfrom[i] <= 'z')
        {
            transfrom[i] -= 32;
        }
    }
    write(sock_fd, transfrom.c_str(), transfrom.size());
    lg.LogMessage(Info, "[%s] transform the word: [%s] -> %s\n", addr.PrintAddr().c_str(), word, transfrom.c_str());
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }
    uint16_t port = std::stoi(argv[1]);
    // 将服务器守护进程化
    Daemon(false, false);
    // 把后续的日志信息打到对应文件上
    lg.LogOption(FileDiv);

    // TcpServer ts(port);
    std::unique_ptr<TcpServer> ts = std::make_unique<TcpServer>(port);
    ts->RegisterFunc("ping", Ping);
    ts->RegisterFunc("translate", Translate);
    ts->RegisterFunc("transform", Transform);

    ts->Init();

    ts->Start();
}

